<?php
namespace app\know\validate;

use app\know\model\ChapterModel;
use think\Validate;
use think\facade\Log;

class ChapterValidate extends Validate
{
    protected $rule = [
        'relate_uuid' => 'require|length:32',
		'type' => 'require|min:1',
		'name' => 'require|min:1:checkName',
		'level' => 'require|integer|gt:0',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'relate_uuid.require' => '关联ID为必填项',
        'relate_uuid.length' => '关联ID不能为空',		
        'name.require' => '名称为必填项',
        'name.min' => '名称不能为空',
        'type.require' => '类型为必填项',
        'type.min' => '类型不能为空',
        'level.require' => '层级为必填项',
        'level.integer' => '层级必须为数字',
		'level.gt' => '层级必须大于0',
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['relate_uuid', 'name' , 'type'],
        'edit' => ['id'],
        'delete' => ['id'],
    ];

    protected function checkName($value, $rule, $data)
    {
        $model = new ChapterModel();
        $item  = $model->where('type', $data['type'])
					   ->where('relate_uuid', $data['relate_uuid'])
                       ->where('name', $data['name'])
					   ->where('level', $data['level'])
                       ->find();

        if (empty($item)) {
            return true;
        } else {
            return '层级:' . $data['level'] . "---已经存在---" . $item['name'];
        }
    }
}